package com.acme.cli;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class BankClient {

	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;

	void run() {
		try {
			requestSocket = new Socket("localhost", 2004);
			System.out.println("Connected to localhost in port 2004");
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			out.flush();
			in = new ObjectInputStream(requestSocket.getInputStream());
			BufferedReader localInput = new BufferedReader(
					new InputStreamReader(System.in));
			try {
				System.out.println(in.readObject());
				do {
					try {
						System.out.print("> ");
						message = localInput.readLine();
						sendMessage(message);
						System.out.println(in.readObject());
					} catch (ClassNotFoundException classNot) {
						System.err.println("data received in unknown format");
					}
				} while (!message.equals("bye"));
			} catch (ClassNotFoundException classNot) {
				System.out.println("unsupported server");
			}
		} catch (UnknownHostException unknownHost) {
			System.err.println("You are trying to connect to an unknown host!");
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}

	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}

}
